import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface User {
  id: string;
  username: string;
  name: string;
  email?: string;
  avatar?: string;
  roles: string[];
  permissions: string[];
  organizationId?: string;
  organizationName?: string;
  departmentId?: string;
  departmentName?: string;
  tenantId: string;
}

interface AuthState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  login: (user: User, token: string) => void;
  logout: () => void;
  updateUser: (user: Partial<User>) => void;
  hasPermission: (permission: string) => boolean;
  hasRole: (role: string) => boolean;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      token: null,
      isAuthenticated: false,

      login: (user: User, token: string) => {
        // 同时设置localStorage，与api.ts保持一致
        if (typeof window !== 'undefined') {
          localStorage.setItem('auth-token', token);
          localStorage.setItem('auth-user', JSON.stringify(user));
        }
        
        set({
          user,
          token,
          isAuthenticated: true
        });
      },

      logout: () => {
        // 清除localStorage，与api.ts保持一致
        if (typeof window !== 'undefined') {
          localStorage.removeItem('auth-token');
          localStorage.removeItem('auth-user');
        }
        
        set({
          user: null,
          token: null,
          isAuthenticated: false
        });
      },

      updateUser: (userData: Partial<User>) => {
        const { user } = get();
        if (user) {
          set({
            user: { ...user, ...userData }
          });
        }
      },

      hasPermission: (permission: string) => {
        const { user } = get();
        return user?.permissions?.includes(permission) || false;
      },

      hasRole: (role: string) => {
        const { user } = get();
        return user?.roles?.includes(role) || false;
      }
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        user: state.user,
        token: state.token,
        isAuthenticated: state.isAuthenticated
      })
    }
  )
);

// 初始化时从localStorage恢复状态（如果zustand persist失败的话）
if (typeof window !== 'undefined') {
  const storedToken = localStorage.getItem('auth-token');
  const storedUser = localStorage.getItem('auth-user');
  
  if (storedToken && storedUser && !useAuthStore.getState().token) {
    try {
      const user = JSON.parse(storedUser);
      useAuthStore.getState().login(user, storedToken);
    } catch (error) {
      console.error('Failed to restore auth state from localStorage:', error);
      localStorage.removeItem('auth-token');
      localStorage.removeItem('auth-user');
    }
  }
}